﻿$(function () {
	prepareBehaviors();
});
// pass context to rewire behaviors on passed elements only (use that when u parse html strings)
function prepareBehaviors(context) {
	// group data-behavior, and run functions with prepare-name of behavior
	var $allbehaviors;
	if (context == null)
		$allbehaviors = $("[data-behavior]");
	else
		$allbehaviors = $("[data-behavior]", context);

	$.each($allbehaviors, function (i, o) {
		try {
			var fn = $(this).attr("data-behavior"),
			callfn = eval("prepare" + fn);
			if (typeof callfn == 'function') {
				callfn.call($(this), context); // pass context to force rewire (until now i couldnt find a reason to)
			}
		} catch (e) {
			// faill silently
			// 
		}

	});
}

/***************BEHAVIORS****************************/
// client tabs associated with plugin
function prepareClientTabs() {

	var $subclienttabs = $(".subclienttabs").hide();
	this.ShClientTabs({
		onSelect: function (o) {
			$subclienttabs.hide();
			$("#" + $(o.srcElement).attr("data-subid")).show();
		}
	});

}

function prepareRadioGroup() {
	// this belongs to jquery object holding behavior

	var $radiogroup = this,
			container = $radiogroup.attr("data-container"),
			$containers = $radiogroup.find(container);
	if (container == null) container = "label"; // fall back to label

	$radiogroup.find(":radio,:checkbox").click(function () {
		// if selected add class else remove it
		var $t = $(this),
				$container = $t.closest(container);
		// clear classes for radio only
		if ($t.attr("type") == "radio")
			$containers.removeClass("selected");

		if (this.checked) $container.addClass("selected");
		else $container.removeClass("selected");

		// TODO: nice to have, on select stub, maybe should turn this into a plugin? nope, disagree, just an onselect stub

	});

}

// preparing ui dates, this needs to be rewired on ajax calls
function prepareUiDate() {

	// bind just once
	if (this.data("uidatebound") == null) {
		this.datepicker({ dateFormat: $body.data("Localization.DateFormat"), changeMonth: true, changeYear: false
		});


		//	if max date is set, set it
		if (this.attr("data-maxdate")) {
			this.datepicker("option", "maxDate", this.attr("data-maxdate"));
		}
		// if min date is set, set it
		if (this.attr("data-mindate")) {
			this.datepicker("option", "minDate", this.attr("data-mindate"));
		}
		this.data("uidatebound", "true");
		// TODO: nice to have, on blur, double check value entered to conform to rules, if it doesnt reset it
	}

}

function prepareDateRange() {
	if (this.data("daterangebound") == null) {

		// first bind uidates

		var dates = this.find("[data-from], [data-to]");
		dates.each(function () {
			prepareUiDate.call($(this));
		});
		dates.datepicker("option",
				"onSelect", function (selectedDate) {
					var option = $(this).is("[data-from]") ? "minDate" : "maxDate",
							instance = $(this).data("datepicker"),
							date = $.datepicker.parseDate(
								instance.settings.dateFormat ||
								$.datepicker._defaults.dateFormat,
								selectedDate, instance.settings);
					dates.not(this).datepicker("option", option, date);
				}

				);
		this.data("daterangebound", "true");
	}
}

/* behavior to associate clicks to epxand/collapse their guts */
function prepareExpandList() {
	// if data-toggleclass is assigned pass it, else assume default
	this.ShExpandList({
		onToggle: function (s) {
			this.toggleClass(this.attr("data-toggleclass") || "toggle");
		},
		guts: '>.guts',
		src: '>.h'
	});
}
/* behavior to associate clicks to expand once, it shows guts then it disappears */
function prepareExpandOnce() {
	this.ShExpandList({
		onShow: function (s) {
			s.srcElement.remove();
		},
		guts: '>.guts',
		src: '>.h'
	});
}
/* behavior to associate show and hide with change in label */
function prepareExpandWithLabel() {
	var slabel, hlabel;
	if (this.attr("data-ismono") === "true") {
		this.find("li:gt(" + (this.attr("data-listsize") - 1) + ")").addClass("guts");
	}
	this.ShExpandList({
		onInit: function (s) {
			slabel = s.srcElement.attr("data-showlabel");
			hlabel = s.srcElement.attr("data-hidelabel");
			(s.state == "show") ? s.srcElement.html(hlabel) : s.srcElement.html(slabel);
			if (s.gutsElement.length == 0) s.srcElement.hide();
		},
		onToggle: function (s) {
			this.toggleClass(this.attr("data-toggleclass") || "toggle");
		},
		onShow: function (s) {
			s.srcElement.html(hlabel);
		},
		onHide: function (s) {
			s.srcElement.html(slabel);
		},
		guts: '.guts',
		src: '>.h'
	});
}
/* behavior for filter list of search results */
function prepareFilterList() {

	var $t = this,
		$selected = this.find(".guts li.selected"),
		$first = this.find(".guts li:first");

	this.ShExpandList({
		onToggle: function (s) {
			this.toggleClass(this.attr("data-toggleclass") || "toggle");
		},
		guts: '>.guts',
		src: '>.h'
	});

	$(document.body).click(function (e) {

		if (!jQuery.contains($t.get(0), e.target)) {
			$t.ShExpandList("hide");
		}
	});

	this.find(".h").html(($selected.length > 0 ? $selected : $first).html());

}
// added oct 7
function prepareEnterClick() {
	// onkeypress of data-input fire a click on data-link// for all inputs attached click link
	var $t = this,
		inputs = this.attr("data-input").split(",");
	for (var i = 0; i < inputs.length; i++) {
		$t.find("#" + $.trim(inputs[i])).keypress(function (e) {
			if (e.which == 13) {
				e.preventDefault();
				simulateClick($t.find("#" + $t.attr("data-link")).get(0));
			}
		});
	}

}
// use this to fire click on links
function simulateClick(obj) {
	if (document.createEvent) {
		var evt = document.createEvent("MouseEvents");
		evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		obj.dispatchEvent(evt);
	} else {
		obj.click();
	}
}

function prepareConfirmLink() {
	// use this for all confirm on clicks messages, make sure the link has a default
	this.click(function (e) {
		var $this = $(this);
		// TODO override confirm
		if (!window.confirm($this.attr("cmessage").replace(/\\n/gim, "\n"))) {
			e.preventDefault();
			return false;
		}
	});
}

function prepareWizarList() {
	// strip a tags from anything that comes after selected li
	var boff = false;
	$.each(this.find(">li"), function () {
		var $t = $(this);
		if ($t.hasClass("selected") || boff) {
			boff = true;
			$t.find("a").contents().unwrap();
		}
	});
}
// TO BE PROMOTED"
function prepareEditInPlace() {
	// when clicked make text area or textbox, show two buttons to save and cancel
	var $t = this;
	this.find(".itemcontent").click(function (e) {
		var $itemcontent = $(this).hide(),
			originalHtml = $itemcontent.html();
		$("<input type='text' />").appendTo($t).val(originalHtml);

	});
}